package com.bruce.apkinstaller.install;

import android.content.pm.IPackageManager;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2018/1/17.
 */

public class PmInstallerModel {
    private static final String TAG = PmInstallerModel.class.getSimpleName();

    /**
     * 调用系统卸载模块
     * <p>
     *
     * @param apkAbsolutePath
     * @throws NoSuchMethodException
     */
    public static void pmUnistall(String apkAbsolutePath, ProductPmUninstallImpl.PmPackageDeleteObserver observer) throws FileNotFoundException {
        Log.d(TAG, "installing: " + apkAbsolutePath);
        try {
            Class<?> clazz = Class.forName("android.os.ServiceManager");
            Method method_getService = clazz.getMethod("getService", String.class);
            IBinder bind = (IBinder) method_getService.invoke(null, "package");
            IPackageManager iPm = IPackageManager.Stub.asInterface(bind);
            iPm.deletePackageAsUser(apkAbsolutePath, observer, 2, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 调用系统安装模块
     * <p>
     * 参考：https://www.cnblogs.com/zhujiabin/p/7458025.html
     *
     * @param apkAbsolutePath
     */
    public static void pmInstall(String apkAbsolutePath, ProductPmInstallImpl.PmPakcageInstallObserver observer) {
        Log.d(TAG, "installing: " + apkAbsolutePath);
        File apkFile = new File(apkAbsolutePath);
        try {
            Class<?> clazz = Class.forName("android.os.ServiceManager");
            Method method_getService = clazz.getMethod("getService", String.class);
            IBinder bind = (IBinder) method_getService.invoke(null, "package");
            IPackageManager iPm = IPackageManager.Stub.asInterface(bind);
            iPm.installPackage(Uri.fromFile(apkFile), observer, 2, apkFile.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
